//
//  MineCenterVC.swift
//  ShareUmbrella
//
//
//  Created by niupark on 2017/8/7.
//  Copyright © 2017年 yourshares. All rights reserved.
//

import UIKit
import SnapKit
import SDWebImage
import YSKit
import RxSwift

class ImagePreviewViewController: YSBaseViewController, UIScrollViewDelegate , YSMediaPickerDelegate {

    let scrollView = UIScrollView()
    let imageView = UIImageView()
    private var uploadObservable:Observable<UserUploaderStatus?>?

    private lazy var mediaPicker: YSMediaPicker = ({return YSMediaPicker(delegate: self)}())

    private func makeBarIconButton(image: UIImage?, title: String?, target: AnyObject?, action: Selector) -> UIBarButtonItem {
        
        let button = UIButton(type: UIButtonType.system).ys.customize { (view) in
            
            view.setImage(image, for: .normal)
            view.titleLabel?.font = YSFont.t05.font
            view.setTitleColor(.white, for: .normal)
            view.frame = CGRect(x: 15, y: 12, width: 20, height: 20)
            view.addTarget(target, action: action, for: .touchUpInside)
            view.ys.handleTheme { [weak view] in
                
                guard let view = view else {
                    return
                }
                view.setTitle(title, for: .normal)
            }
            
        }
        
        return UIBarButtonItem(customView: button)
    }

    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
    
    override func setup() {
        super.setup()
        self.showCustomNavigationBar = true
        
    }
    
    override func customNavigationConfig(_ config: YSNavagtionConfig) {
        config.backgourdColor = .black
        config.backImageTintColor = .white
    }

    override func buildUI() {
        super.buildUI()
        self.customTitleItem?.rightBarButtonItems = YSUI.UIManager.makeBarButtonItems([
            self.makeBarIconButton(image: nil, title: "更多", target: self, action: #selector(actionRight))
            ])

        
        self.scrollView.ys.customize { (view) in
            self.view.addSubview(view)
            view.backgroundColor = .black
            view.delegate = self
//            view.maximumZoomScale = 1.5
//            view.minimumZoomScale = 0.5
            view.snp.makeConstraints({ (make) in
                make.bottom.top.leading.trailing.equalTo(self.view)
            })
        }
        
        self.imageView.ys.customize { (view) in
            self.scrollView.addSubview(view)
//            view.center = self.scrollView.center
//            view.frame = CGRect(x: 0, y: 0, width: YSUI.UIManager.screenWidth, height: YSUI.UIManager.screenWidth)
//            view.center = self.view.center

            view.snp.makeConstraints({ (make) in
                make.center.equalTo(self.scrollView)
                make.leading.trailing.equalTo(self.view)
                make.height.equalTo(self.scrollView.snp.width)
            })
        }
        
    }
    
    override func buildRx() {
        super.buildRx()
        
        _  = UserService.sharedInstance.headLogo.asObservable().takeUntil(self.rx.deallocated).subscribe(onNext: { [weak self] (headLogo) in
            guard let `self` = self else {
                return
            }
            self.imageView.sd_setImage(with: URL(string: headLogo ?? ""), placeholderImage: UIImage(named: "空白头像"))
        })

    }
    
    public func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return self.imageView
    }
    
    func actionRight() {
        //显示左边
        self.uploadHeadlogo()

    }
    
    func uploadHeadlogo() {
        
        // 相册中选择图片
        let actionHandler1: YSActionHandler = { [unowned self] index in
            // 分别对一个原始图片和裁剪过的图片
            _ = self.mediaPicker.selectImage(editable: true).takeUntil(self.rx.deallocated).subscribe(onNext: { [unowned self](images) in
                // 获取裁剪图片并且裁剪为正方形
                guard let editImage = images.1 else {
                    return
                }
                
                
                editImage.ys.compressImage(CGSize(width: 200, height: 200), maxDataSize: 50, handler: { (data) in
                    guard let mydata = data, let image = UIImage(data: mydata) else {
                        return
                    }
                    
                    
                    HUD.show()
                    _ = YSNetWorkManager.provider.requestJSON(YSStructTarget(UserAPI.updateUserHeader(token: Auth.token, phone: UserService.sharedInstance.phone.value!, imageData: image))).subscribe(onNext: { [weak self] (data) in
                        //
                        HUD.hide()
                        guard self != nil else {
                            return
                        }
                        
                        guard let `data` = data else {
                            return
                        }
                        UserService.sharedInstance.headLogo.value = `data`["data"]["url"].string
                        
                        
                        }, onError: { [weak self](ErrorType) in
                            HUD.hide()
                            guard let  `self` = self else {
                                return
                            }
                            self.handle(withError: ErrorType, targetVC: self)
                    })
                    
                    
                })
                

                
            })
        }
        
        // 拍摄图片
        let actionHandler2: YSActionHandler = { [unowned self] index in
            //
            if UIImagePickerController.isCameraDeviceAvailable(.rear) {
                _ = self.mediaPicker.takePhoto(editable: true).takeUntil(self.rx.deallocated).subscribe(onNext: { [unowned self](images) in
                    // 获取裁剪图片并且裁剪为正方形,images.1?.subImage()已经是正方形，不需要选取
                    guard let editImage = images.1 else {
                        return
                    }
                    
                    
                    editImage.ys.compressImage(CGSize(width: 200, height: 200), maxDataSize: 50, handler: { (data) in
                        guard let mydata = data, let image = UIImage(data: mydata) else {
                            return
                        }
                        
                        
                        HUD.show()
                        
                        var parameters: [String: Any] = [:]
                        parameters["token"] = Auth.token
                        parameters["avator"] =  UserService.sharedInstance.phone.value!+".png"

                        self.uploadObservable = UserInfoViewModel.uploader(parameters, fileName:parameters["avator"] as! String, image: image)
                        self.uploadObservable?.subscribe(onNext: { [weak self] (result) in
                            guard let status = result else{
                                return
                            }
                            switch status {
                            case .uploading(let progress):
                                HUD.hide()
                                
                                print("上传了 \(progress)")
                            case .error:
                                print("上传失败")
                                HUD.hide()
                                
                            case .completed(let imageKey):
                                print("上传成功 \(imageKey)")
                                UserService.sharedInstance.headLogo.value = imageKey
                                HUD.hide()

                            }
                            
                            }, onError: { [weak self](error) in
                                guard let  `self` = self else {
                                    return
                                }

                                self.handle(withError: error, targetVC: self)
                                HUD.hide()
                                
                        })

                        
                    })
                    

                })
                
            }
        }
        let action1 = YSActionItem(title: I18n("setting.pickimage.album"), action: actionHandler1, status: .normal, image: nil)
//        let action2 = YSActionItem(title: I18n("setting.pickimage.photo"), action: actionHandler2, status: .normal, image: nil)
        
        //let sheet = YSSheetView(actionItems: [action1, action2])
        let sheet = YSSheetView(actionItems: [action1])
        sheet.show()
        
        
    }
    
    // MARK: - YSMediaPickerDelegate
    func presentPicker(_ picker: UIImagePickerController) {
        self.present(picker, animated: true, completion: nil)
    }
    
    func dismissPicker(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
    
    


}
